#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QProcess>

#include<QTimer>
#include"logwriter.h"
#include"blockqueue.h"
#include<QScrollBar>
#include <QFileDialog>
#include <QPushButton>

#ifdef Q_OS_WIN
#include <windows.h>
#include <tlhelp32.h>
#include <iphlpapi.h>
#include <psapi.h>
#include<wlanapi.h>

typedef unsigned long DWORD;
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib,"wlanapi.lib")

#elif defined(Q_OS_LINUX)
#include <sys/types.h>
typedef pid_t DWORD;

#endif

QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

struct ProcessInfo
{
    DWORD pid;
    QString name;
    QString cpuUsage;
    QString memoryUsage;
    QString netState;
    QString localIpPort;
#ifdef Q_OS_WIN
    FILETIME lastKernelTime = {0, 0};
    FILETIME lastUserTime = {0, 0};
#elif defined(Q_OS_LINUX)
    long lastKernelTime = 0;
    long lastUserTime = 0;
    long lastTotalJiffies = 0;
#endif
};

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();


    void initTable();
    void loadProcesses();

    void startMonitoring(DWORD pid);

    void updateTableRow(int row);


    QString getMemoryUsage(DWORD pid);
    float calculateCPUUsage(DWORD pid);

    void updateNetworkInfo();


    void checkNetworkStatusAndRestart();

    void stopMonitoring();
#ifdef Q_OS_WIN
    QString formatIp(DWORD ip);
    QString formatPort(WORD port);
#elif defined(Q_OS_LINUX)
    QString formatLinuxIp(const QString &ipHex);
    QString formatLinuxPort(const QString &portHex);
#endif

    QList<DWORD> findPidByProcessName(const QString& processName);

    bool isPidUsingTargetPort(DWORD pid, const DWORD targetPort);



    bool isPhysicalNetworkConnected();


    bool killAllOldProcesses(DWORD pid);

private slots:
    void on_startButton_clicked();
    void on_processErrorOccurred();

    void updateProcessInfo();

    void restartServer();


    void on_selectButton_clicked();




private:
    Ui::Widget *ui;
    bool isSelect;

private:
    bool isMonitoring;//是否已经开始监测
    DWORD serverPid = 0; // 仅保存服务器 PID，用于监控
    QString serverPath;  // 保存服务器路径，用于重启
    QTimer*updateTimer;
    ProcessInfo monitoredProcess;  // 被监测的进程信息

    bool networkProblemDetected;//网络是否有异常
    QString lastNetworkState;//上一次的网络状态


    LogWriter*logwriter;

    bool isRestarting; // 是否重启

    bool lastPhysicalNetworkState=true;

    bool isNetworkDisconnected=false;


};
#endif // WIDGET_H
